﻿#include <iostream>
#include <Python.h>

// 数字相加
static PyObject* cpyAdd(PyObject* self, PyObject* args)
{
    long long a, b;
    if (!PyArg_ParseTuple(args, "LL", &a, &b))
    {
        return NULL;
    }
    return PyLong_FromLongLong(a + b);
}

// 字符串拼接
static PyObject* cpyStringAdd(PyObject* self, PyObject* args)
{
    const char* str1;
    const char* str2;
    if (!PyArg_ParseTuple(args, "ss", &str1, &str2))
    {
        return NULL;
    }
    std::string newStr{ str1 };
    newStr.append(str2);
    return PyUnicode_FromString(newStr.c_str());
}

// sumTo
static PyObject* cpySumTo(PyObject* self, PyObject* args)
{
    int start;
    int endTo;
    int length;
    if (!PyArg_ParseTuple(args, "iii", &start, &endTo, &length))
    {
        return NULL;
    }
    long long sumValue = 0;
    for (int i = start; i < endTo; i += length)
    {
        sumValue += i;
    }
    return PyLong_FromLongLong(sumValue);
}

static PyMethodDef TestCPyLib_Methods[] = {
    {"cpyAdd", cpyAdd, METH_VARARGS, NULL},
    {"cpyStringAdd", cpyStringAdd, METH_VARARGS, NULL},
    {"cpySumTo", cpySumTo, METH_VARARGS, NULL},
    {NULL, NULL, 0, NULL},
};

static struct PyModuleDef moduleDefine = {
    PyModuleDef_HEAD_INIT,
    "TestCPyLib",
    "这是一个CPY测试模块",
    -1,
    TestCPyLib_Methods
};

PyMODINIT_FUNC PyInit_TestCPy(void)
{
    return PyModule_Create(&moduleDefine);
}